package Utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public abstract class RequestIOTools {
    public static String encodeURL(String source, String encodeFunction) {
        String result;
        try { result = URLEncoder.encode(source, encodeFunction); }
        catch(UnsupportedEncodingException e) { e.printStackTrace(); return "0"; }
        return result;
    }

    public static String sendRequest(String url, String requestMethod) {
        StringBuffer sb = new StringBuffer();
        try {
            URL requestUrl = new URL(url);
            HttpURLConnection requestConnection = (HttpURLConnection)requestUrl.openConnection();
            requestConnection.setDoOutput(false);
            requestConnection.setUseCaches(false);
            requestConnection.setDoOutput(true);
            requestConnection.setRequestMethod(requestMethod);

            // (  0 ^ 0 ) Stream --> String
            InputStream inputStream = requestConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader readerBuffer = new BufferedReader(inputStreamReader);
            String resultString = null;
            while(((resultString = readerBuffer.readLine()) != null)) {
                sb.append(resultString);
            }

            // ( & √ & ) Clean data
            readerBuffer.close();
            inputStream.close();
            inputStreamReader.close();
            requestConnection.disconnect();
        }

        catch(Exception e) { e.printStackTrace(); }
        return sb.toString();
    }
}
